<?php

namespace App\Services;

use App\Models\CartItem;
use App\Models\Cart;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class CartPriceService
{
    /**
     * 更新购物车中所有商品的价格
     */
    public function updateCartPrices(Cart $cart): array
    {
        $priceChanges = [];
        
        foreach ($cart->items as $item) {
            $priceInfo = $this->updateItemPrice($item);
            if ($priceInfo['changed']) {
                $priceChanges[] = $priceInfo;
            }
        }
        
        return $priceChanges;
    }
    
    /**
     * 更新单个商品的价格
     */
    public function updateItemPrice(CartItem $item): array
    {
        $currentPrice = $item->variant ? $item->variant->price : $item->product->price;
        
        // 更新当前价格
        $item->updateCurrentPrice();
        
        // 检查价格是否变动
        $priceInfo = $item->getPriceChangeInfo();
        
        if ($priceInfo['changed']) {
            Log::info('Cart item price changed', [
                'cart_item_id' => $item->id,
                'product_id' => $item->product_id,
                'variant_id' => $item->variant_id,
                'original_price' => $priceInfo['original_price'],
                'current_price' => $priceInfo['current_price'],
                'change_amount' => $priceInfo['change_amount'],
                'change_percentage' => $priceInfo['change_percentage'],
            ]);
        }
        
        return $priceInfo;
    }
    
    /**
     * 获取购物车价格变动摘要
     */
    public function getCartPriceSummary(Cart $cart): array
    {
        $items = $cart->items;
        $totalOriginalPrice = 0;
        $totalCurrentPrice = 0;
        $priceChanges = [];
        
        foreach ($items as $item) {
            $priceInfo = $item->getPriceChangeInfo();
            $totalOriginalPrice += $priceInfo['original_price'] * $item->quantity;
            $totalCurrentPrice += $priceInfo['current_price'] * $item->quantity;
            
            if ($priceInfo['changed']) {
                $priceChanges[] = [
                    'item' => $item,
                    'price_info' => $priceInfo,
                ];
            }
        }
        
        $totalChangeAmount = $totalCurrentPrice - $totalOriginalPrice;
        $totalChangePercentage = $totalOriginalPrice > 0 
            ? round(($totalChangeAmount / $totalOriginalPrice) * 100, 2) 
            : 0;
        
        return [
            'total_original_price' => $totalOriginalPrice,
            'total_current_price' => $totalCurrentPrice,
            'total_change_amount' => $totalChangeAmount,
            'total_change_percentage' => $totalChangePercentage,
            'has_changes' => count($priceChanges) > 0,
            'changed_items' => $priceChanges,
            'changed_items_count' => count($priceChanges),
        ];
    }
    
    /**
     * 生成价格变动通知消息
     */
    public function generatePriceChangeNotification(array $summary): string
    {
        if (!$summary['has_changes']) {
            return '';
        }
        
        $message = "购物车中有 {$summary['changed_items_count']} 个商品价格发生变动：\n\n";
        
        foreach ($summary['changed_items'] as $itemData) {
            $item = $itemData['item'];
            $priceInfo = $itemData['price_info'];
            
            $changeText = $priceInfo['change_amount'] > 0 ? '上涨' : '下降';
            $changeAmount = abs($priceInfo['change_amount']);
            $changePercentage = abs($priceInfo['change_percentage']);
            
            $message .= "• {$item->product->name}：\n";
            $message .= "  原价：¥{$priceInfo['original_price']} → 现价：¥{$priceInfo['current_price']}\n";
            $message .= "  {$changeText} ¥{$changeAmount} ({$changePercentage}%)\n\n";
        }
        
        if ($summary['total_change_amount'] != 0) {
            $totalChangeText = $summary['total_change_amount'] > 0 ? '上涨' : '节省';
            $totalChangeAmount = abs($summary['total_change_amount']);
            $totalChangePercentage = abs($summary['total_change_percentage']);
            
            $message .= "总金额变动：{$totalChangeText} ¥{$totalChangeAmount} ({$totalChangePercentage}%)";
        }
        
        return $message;
    }
    
    /**
     * 批量更新购物车价格（用于定时任务）
     */
    public function batchUpdateAllCartPrices(): array
    {
        $carts = Cart::with(['items.product', 'items.variant'])->get();
        $totalChanges = [];
        
        foreach ($carts as $cart) {
            $changes = $this->updateCartPrices($cart);
            if (!empty($changes)) {
                $totalChanges[$cart->id] = $changes;
            }
        }
        
        Log::info('Batch cart price update completed', [
            'carts_processed' => $carts->count(),
            'carts_with_changes' => count($totalChanges),
        ]);
        
        return $totalChanges;
    }
}
